package com.emiage.ddutils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author MaTianyu
 * @date 2014-12-10
 */
public class ApkUtil {

	/**
	 * 调用系统分享
	 */
	public static void shareToOtherApp(Context context, String title, String content, String dialogTitle) {
		Intent intentItem = new Intent(Intent.ACTION_SEND);
		intentItem.setType("text/plain");
		intentItem.putExtra(Intent.EXTRA_SUBJECT, title);
		intentItem.putExtra(Intent.EXTRA_TEXT, content);
		intentItem.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(Intent.createChooser(intentItem, dialogTitle));
	}

	/**
	 * need < uses-permission android:name =“android.permission.GET_TASKS” />
	 * 判断是否前台运行
	 */
	public static boolean isRunningForeground(Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> taskList = am.getRunningTasks(1);
		if (taskList != null && !taskList.isEmpty()) {
			ComponentName componentName = taskList.get(0).topActivity;
			if (componentName != null && componentName.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取App包 信息版本号
	 *
	 * @param context
	 * @return
	 */
	public PackageInfo getPackageInfo(Context context) {
		PackageManager packageManager = context.getPackageManager();
		PackageInfo packageInfo = null;
		try {
			packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return packageInfo;
	}

	/**
	 * 安装apk
	 *
	 * @param context 上下文
	 * @param path    apk路径
	 */
	public static void InstallApk(Context context, String path) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(path)),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	/**
	 * 卸载apk
	 *
	 * @param context 上下文
	 * @param pkName  包名
	 */
	public static void UnInstallApk(Context context, String pkName) {
		Uri packageURI = Uri.parse(pkName);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		context.startActivity(uninstallIntent);
	}

	/**
	 * 通过包名启动app
	 *
	 * @param context 上下文
	 * @param pkName  包名
	 */
	public static void OpenApp(Context context, String pkName) {
		Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkName);
		context.startActivity(intent);
	}

	/**
	 * 静默安装
	 *
	 * @param file
	 * @return 是否成功
	 */
	public static boolean slientInstall(File file) {
		boolean result = false;
		Process process = null;
		OutputStream out = null;
		try {
			process = Runtime.getRuntime().exec("su");
			out = process.getOutputStream();
			DataOutputStream dataOutputStream = new DataOutputStream(out);
			dataOutputStream.writeBytes("chmod 777 " + file.getPath() + "\n");
			dataOutputStream.writeBytes("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install -r " +
					file.getPath());
			// 提交命令
			dataOutputStream.flush();
			// 关闭流操作
			dataOutputStream.close();
			out.close();
			int value = process.waitFor();

			// 代表成功
			if (value == 0) {
				result = true;
			} else if (value == 1) { // 失败
				result = false;
			} else { // 未知情况
				result = false;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 安装到系统目录下(system/app)
	 *
	 * @param context 上下文
	 * @param name    应用名
	 */
	public static void toSystemApp(Context context, String name) {
		String packageName = context.getPackageName();
		String[] commands = {"busybox mount -o remount,rw /system",
				"busybox cp /data/data/" + packageName + "/files/" + name + " /system/app/" + name,
				"busybox rm /data/data/" + packageName + "/files/" + name};
		Process process = null;
		DataOutputStream dataOutputStream = null;
		try {
			process = Runtime.getRuntime().exec("su");
			dataOutputStream = new DataOutputStream(process.getOutputStream());
			int length = commands.length;
			for (int i = 0; i < length; i++) {
				LogUtils.d("commands[" + i + "]:" + commands[i]);
				dataOutputStream.writeBytes(commands[i] + "\n");
			}
			dataOutputStream.writeBytes("exit\n");
			dataOutputStream.flush();
			process.waitFor();
		} catch (Exception e) {
			LogUtils.d("copy fail" + e);
		} finally {
			try {
				if (dataOutputStream != null) {
					dataOutputStream.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 安装到手机(data/app)目录下
	 *
	 * @param context 上下文
	 * @param name    应用名
	 */
	public static void toDataApp(Context context, String name) {
		String packageName = context.getPackageName();
		String[] commands = {"busybox mount -o remount,rw /system",
				"busybox cp /data/data/" + packageName + "/files/" + name + " /data/app/" + name,
				"busybox rm /data/data/" + packageName + "/files/" + name};
		Process process = null;
		DataOutputStream dataOutputStream = null;
		try {
			process = Runtime.getRuntime().exec("su");
			dataOutputStream = new DataOutputStream(process.getOutputStream());
			int length = commands.length;
			for (int i = 0; i < length; i++) {
				LogUtils.d("commands[" + i + "]:" + commands[i]);
				dataOutputStream.writeBytes(commands[i] + "\n");
			}
			dataOutputStream.writeBytes("exit\n");
			dataOutputStream.flush();
			process.waitFor();
		} catch (Exception e) {
			LogUtils.d("copy fail" + e);
		} finally {
			try {
				if (dataOutputStream != null) {
					dataOutputStream.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * 启动应用
	 */
	public static boolean startAppByPackageName(Context context, String packageName) {
		return startAppByPackageName(context, packageName, null);
	}

	/**
	 * 启动应用
	 */
	public static boolean startAppByPackageName(Context context, String packageName, Map<String, String> param) {
		android.content.pm.PackageInfo pi = null;
		try {
			pi = context.getPackageManager().getPackageInfo(packageName, 0);
			Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
			resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
				resolveIntent.setPackage(pi.packageName);
			}

			List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0);

			ResolveInfo ri = apps.iterator().next();
			if (ri != null) {
				String packageName1 = ri.activityInfo.packageName;
				String className = ri.activityInfo.name;

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);

				ComponentName cn = new ComponentName(packageName1, className);

				intent.setComponent(cn);
				if (param != null) {
					for (Map.Entry<String, String> en : param.entrySet()) {
						intent.putExtra(en.getKey(), en.getValue());
					}
				}
				context.startActivity(intent);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context.getApplicationContext(), "启动失败",
					Toast.LENGTH_LONG).show();
		}
		return false;
	}


	/**
	 * 添加快捷图标
	 * @param context
	 * @param idName	名称
	 * @param idLogo	logo图片
	 */
	public void addShortcut(Context context,int idName,int idLogo) {
		String ACTION_INSTALL_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
		// 快捷方式要启动的包
		Intent intent = new Intent(context, context.getClass());
		intent.setAction(Intent.ACTION_MAIN);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

		// 设置快捷方式的参数
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		// 设置名称
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getResources()
				.getString(idName)); // 设置启动 Intent
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
		// 设置图标
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(context,
						idLogo));
		// 只创建一次快捷方式
		shortcutIntent.putExtra("duplicate", false);

		// 创建
		context.sendBroadcast(shortcutIntent);

	}

	/**
	 * 检查是否已经创建图标
	 * @param context
	 * @return
	 */
	public boolean hasShortcut(Context context) {
		boolean result = false;
		// 获取当前应用名称
		String title = null;
		try {
			final PackageManager pm = context.getPackageManager();
			title = pm.getApplicationLabel(
					pm.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA)).toString();
		} catch (Exception e) {
		}
		final String uriStr;
		if (android.os.Build.VERSION.SDK_INT < 8) {
			uriStr = "content://com.android.launcher.settings/favorites?notify=true";
		} else {
			uriStr = "content://com.android.launcher2.settings/favorites?notify=true";
		}

		Uri CONTENT_URI = Uri.parse(uriStr);
		Cursor c = context.getContentResolver().query(CONTENT_URI, null,
				"title=?", new String[] { title }, null);
		if (c != null && c.getCount() > 0) {
			result = true;

			if(!c.isClosed())
				c.close();
		}

		c = null;

		return result;
	}

	/**
	 * 删除程序的快捷方式
	 */
	private void delShortcut(Activity context){
		Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");

		//快捷方式的名称
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));

		//指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
		//注意: ComponentName的第二个参数必须是完整的类名（包名+类名），否则无法删除快捷方式
		String appClass = context.getPackageName() + "." +context.getLocalClassName();
		ComponentName comp = new ComponentName(context.getPackageName(), appClass);
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));

		context.sendBroadcast(shortcut);
	}

}
